package com.pine.manager.pineframework.trigger.impl;

import cn.hutool.core.collection.CollUtil;
import com.pine.common.beans.enums.DeletedEnum;
import com.pine.common.beans.exception.BusinessException;
import com.pine.common.beans.exception.ExceptionCodeEnum;
import com.pine.common.beans.pineframework.request.SysRoleAssignMenuRequest;
import com.pine.common.trigger.TriggerContext;
import com.pine.dao.pineframework.entity.SysRole;
import com.pine.dao.pineframework.entity.SysRoleMenu;
import com.pine.manager.core.TriggerTypeEnum;
import com.pine.manager.pineframework.bo.SysRoleBo;
import com.pine.manager.pineframework.trigger.AbstractTriggerTemplateAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 系统角色分配菜单 触发器
 * </p>
 *
 * @author pine manage
 * @since 2024-08-16
 */
@Component
@Slf4j
public class SysRoleAssignMenuTrigger extends AbstractTriggerTemplateAdapter<SysRoleAssignMenuRequest, Boolean> {

    public SysRoleAssignMenuTrigger() {
        super(TriggerTypeEnum.SYS_ROLE_ASSIGN_MENU);
    }


    @Override
    protected void before(TriggerContext<SysRoleAssignMenuRequest> triggerContext) {
        SysRoleAssignMenuRequest request = triggerContext.getTriggerRequest();
        SysRoleBo oldSysRoleBo = sysRoleManager.getOneByUniqueKey(request.getRoleId(), SysRole::getId);
        if (Objects.isNull(oldSysRoleBo)) {
            throw new BusinessException(ExceptionCodeEnum.USER_ROLE_NOT_EXIST);
        }
    }

    /**
     * 触发
     *
     * @param triggerContext 触发上下文
     * @return 触发结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean trigger(TriggerContext<SysRoleAssignMenuRequest> triggerContext) {
        SysRoleAssignMenuRequest request = triggerContext.getTriggerRequest();
        // 删除角色菜单关联关系
        sysRoleMenuManager.deleteByRoleId(request.getRoleId());

        List<Long> menuIds = request.getMenuIds();
        if (CollUtil.isNotEmpty(menuIds)) {
            List<SysRoleMenu> roleMenus = menuIds.stream().map(menuId -> {
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setRoleId(request.getRoleId());
                sysRoleMenu.setMenuId(menuId);
                sysRoleMenu.setDeleted(DeletedEnum.NOT_DELETED.getCode());
                sysRoleMenu.setCreateTime(LocalDateTime.now());
                return sysRoleMenu;
            }).toList();

            sysRoleMenuManager.saveBatch(roleMenus);
        }
        return true;
    }
}
